<template>
  <div class="crime-warning-chart">
    <div class="chart-header">
      <h3>高发犯罪预警</h3>
      <div class="chart-status">
        <div class="status-indicator" :class="warningLevel">
          <div class="pulse-dot"></div>
          <span>{{ warningLevelText }}</span>
        </div>
      </div>
    </div>

    <div class="chart-container">
      <div id="crime-warning-chart" class="warning-chart"></div>
    </div>

  </div>
</template>

<script>
import { Chart } from '@antv/g2'

export default {
  name: 'CrimeWarningChart',
  data() {
    return {
      warningChart: null,
      warningData: [],
      crimeTypes: ['盗窃', '抢劫', '诈骗', '打架斗殴', '交通违法', '其他'],
      updateTimer: null,
      currentAlertCount: 0,
      currentWarningAreas: 0
    }
  },
  computed: {
    currentAlerts() {
      return this.currentAlertCount + '起'
    },
    warningAreas() {
      return this.currentWarningAreas + '个'
    },
    responseTime() {
      return '3.2分钟'
    },
    warningLevel() {
      if (this.currentAlertCount > 50) return 'critical'
      if (this.currentAlertCount > 30) return 'warning'
      if (this.currentAlertCount > 15) return 'caution'
      return 'normal'
    },
    warningLevelText() {
      const level = this.warningLevel
      switch (level) {
        case 'critical': return '红色预警'
        case 'warning': return '橙色预警'
        case 'caution': return '黄色预警'
        default: return '正常'
      }
    }
  },
  mounted() {
    this.initializeChart()
    // this.startDataUpdate()
  },
  beforeDestroy() {
    if (this.updateTimer) {
      clearInterval(this.updateTimer)
    }
    if (this.warningChart) {
      this.warningChart.destroy()
    }
  },
  methods: {
    initializeChart() {
      this.$nextTick(() => {
        this.initWarningChart()
      })
    },

    initWarningChart() {
      const container = document.getElementById('crime-warning-chart')
      if (!container) return

      this.warningChart = new Chart({
        container: 'crime-warning-chart',
        autoFit: true,
        height: 250,
        theme: 'dark'
      })

      // 生成预警数据
      this.generateWarningData()

      this.warningChart.axis('x', {
        title: false
      })

      this.warningChart.axis('y', {
        title: false
      })

      // 获取历史数据和预测数据的衔接点
      const historicalData = this.warningData.filter(d => !d.isPrediction)
      const predictionData = this.warningData.filter(d => d.isPrediction)
      const lastHistoricalPoint = historicalData[historicalData.length - 1]

      // 历史数据线（实线）
      this.warningChart
        .line()
        .data(historicalData)
        .encode('x', 'year')
        .encode('y', 'alerts')
        .scale('y', { nice: true })
        .style('stroke', '#ff6b34')
        .style('strokeWidth', 2)
        .animate('enter', { type: 'waveIn', duration: 1000 })

      // 预测数据线（虚线）- 包含衔接点以确保连续性
      const predictionLineData = [lastHistoricalPoint, ...predictionData]
      this.warningChart
        .line()
        .data(predictionLineData)
        .encode('x', 'year')
        .encode('y', 'alerts')
        .scale('y', { nice: true })
        .style('stroke', '#ff6b34')
        .style('strokeWidth', 2)
        .style('strokeDasharray', [5, 5])
        .animate('enter', { type: 'waveIn', duration: 1000 })

      // 添加预测数据开始的分隔线
      const predictionStartIndex = this.warningData.findIndex(d => d.isPrediction)
      if (predictionStartIndex >= 0) {
        const predictionStartPoint = this.warningData[predictionStartIndex]
        this.warningChart
          .point()
          .data([predictionStartPoint])
          .encode('x', 'year')
          .encode('y', 'alerts')
          .style('fill', '#ff6b34')
          .style('stroke', '#ffffff')
          .style('strokeWidth', 2)
          .style('r', 6)
          .tooltip({ title: '预测数据起始点' })
      }

      // 区域填充（仅历史数据）
      this.warningChart
        .area()
        .data(historicalData)
        .encode('x', 'year')
        .encode('y', 'alerts')
        .scale('y', { nice: true })
        .style('fill', 'linear-gradient(180deg, rgba(255, 107, 52, 0.3) 0%, rgba(255, 107, 52, 0.05) 100%)')
        .tooltip(false)

      // 预警阈值线（橙色预警）
      const orangeThresholdData = this.warningData.map(d => ({ year: d.year, alerts: 30 }))
      this.warningChart
        .line()
        .data(orangeThresholdData)
        .encode('x', 'year')
        .encode('y', 'alerts')
        .style('stroke', '#ffa500')
        .style('strokeWidth', 1)
        .style('strokeDasharray', [5, 5])
        .tooltip({ title: '橙色预警阈值: 30起' })

      // 严重预警阈值线（红色预警）
      const redThresholdData = this.warningData.map(d => ({ year: d.year, alerts: 50 }))
      this.warningChart
        .line()
        .data(redThresholdData)
        .encode('x', 'year')
        .encode('y', 'alerts')
        .style('stroke', '#ff4444')
        .style('strokeWidth', 1)
        .style('strokeDasharray', [5, 5])
        .tooltip({ title: '红色预警阈值: 50起' })

      this.warningChart.render()
    },

    generateWarningData() {
      this.warningData = []
      const currentYear = new Date().getFullYear()

      // 生成过去3年的历史数据 (22年、23年、24年)
      for (let yearOffset = -3; yearOffset <= -1; yearOffset++) {
        const year = currentYear + yearOffset
        const yearLabel = year >= 2000 ? `${year - 2000}年` : `${year}年`
        const isPrediction = false
        const historicalYearOffset = year - (currentYear - 3) // 重新计算historicalYearOffset

        // 计算年度趋势基数（不含随机波动）
        let baseAlertsWithoutRandom = 0
        if (historicalYearOffset <= 1) { // 早期年份
          baseAlertsWithoutRandom = 10 + historicalYearOffset * 5 + 5 // 中位数 + 趋势
        } else if (historicalYearOffset >= 2 && historicalYearOffset <= 3) { // 中期年份
          baseAlertsWithoutRandom = 20 + historicalYearOffset * 5 + 12.5 // 中位数 + 趋势
        } else { // 近期年份
          baseAlertsWithoutRandom = 30 + historicalYearOffset * 5 + 17.5 // 中位数 + 趋势
        }

        // 历史数据：添加随机波动
        const randomRange = historicalYearOffset <= 1 ? 15 : (historicalYearOffset >= 2 && historicalYearOffset <= 3 ? 25 : 35)
        const baseAlerts = baseAlertsWithoutRandom + (Math.random() - 0.5) * randomRange

        // 历史数据添加随机波动
        const randomFactor = Math.random() * 15 - 7.5
        let alerts = Math.round(baseAlerts + randomFactor)
        alerts = Math.max(5, alerts) // 确保不小于5

        this.warningData.push({
          year: yearLabel,
          alerts,
          isPrediction,
          yearValue: year,
          // 添加犯罪类型分布（可选，用于tooltip）
          breakdown: this.crimeTypes.map(type => ({
            type,
            count: Math.floor(Math.random() * alerts / this.crimeTypes.length)
          }))
        })
      }

      // 生成从25年开始的3年预测数据 (25年、26年、27年)
      for (let yearOffset = 0; yearOffset <= 2; yearOffset++) {
        const year = currentYear + yearOffset
        const yearLabel = year >= 2000 ? `${year - 2000}年` : `${year}年`
        const isPrediction = true

        // 预测数据：基于历史数据的最后一个基准值继续增长
        const lastHistoricalBase = 30 + 2 * 5 + 17.5 // 24年的基准值
        const baseAlerts = lastHistoricalBase + yearOffset * 8 // 从历史末尾连续增长

        // 预测数据使用确定值
        let alerts = Math.round(baseAlerts)
        alerts = Math.max(5, alerts) // 确保不小于5

        this.warningData.push({
          year: yearLabel,
          alerts,
          isPrediction,
          yearValue: year,
          // 添加犯罪类型分布（可选，用于tooltip）
          breakdown: this.crimeTypes.map(type => ({
            type,
            count: Math.floor(Math.random() * alerts / this.crimeTypes.length)
          }))
        })
      }

      // 更新统计数据
      this.currentAlertCount = this.warningData.reduce((sum, item) => sum + item.alerts, 0)
      this.currentWarningAreas = Math.floor(Math.random() * 8) + 3 // 3-10个预警区域
    },

    startDataUpdate() {
      this.updateTimer = setInterval(() => {
        this.updateWarningData()
      }, 4000) // 每4秒更新一次
    },

    updateWarningData() {
      if (!this.warningChart) return

      this.generateWarningData()

      // 更新图表数据
      this.warningChart.changeData(this.warningData)

      // 强制重新渲染
      this.warningChart.render()
    }
  }
}
</script>

<style scoped>
.crime-warning-chart {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 15px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 0 15px;
}

.chart-header h3 {
  margin: 0;
  color: #ff6b34;
  font-size: 16px;
  font-weight: 600;
  text-shadow: 0 0 10px rgba(255, 107, 52, 0.5);
}

.chart-status {
  display: flex;
  align-items: center;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-indicator.normal {
  background: rgba(0, 255, 136, 0.2);
  border: 1px solid rgba(0, 255, 136, 0.3);
  color: #00ff88;
}

.status-indicator.caution {
  background: rgba(255, 255, 0, 0.2);
  border: 1px solid rgba(255, 255, 0, 0.3);
  color: #ffff00;
}

.status-indicator.warning {
  background: rgba(255, 165, 0, 0.2);
  border: 1px solid rgba(255, 165, 0, 0.3);
  color: #ffa500;
}

.status-indicator.critical {
  background: rgba(255, 68, 68, 0.2);
  border: 1px solid rgba(255, 68, 68, 0.3);
  color: #ff4444;
}

.pulse-dot {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  animation: pulse 2s ease-in-out infinite;
}

.status-indicator.normal .pulse-dot { background: #00ff88; }
.status-indicator.caution .pulse-dot { background: #ffff00; }
.status-indicator.warning .pulse-dot { background: #ffa500; }
.status-indicator.critical .pulse-dot { background: #ff4444; }

@keyframes pulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.5;
    transform: scale(1.2);
  }
}

.chart-container {
  flex: 1;
  margin-bottom: 15px;
  background: rgba(0, 0, 0, 0.3);
  border-radius: 8px;
  border: 1px solid rgba(255, 107, 52, 0.1);
  overflow: hidden;
}

.warning-chart {
  width: 100%;
  height: 100%;
}

.warning-summary {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 10px 15px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  margin: 0 15px;
}

.summary-item {
  text-align: center;
}

.summary-item .label {
  display: block;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 4px;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.summary-item .value {
  display: block;
  font-size: 16px;
  font-weight: 700;
  color: #ff6b34;
  text-shadow: 0 0 8px rgba(255, 107, 52, 0.5);
}

.summary-item .value.warning {
  color: #ffa500;
  text-shadow: 0 0 8px rgba(255, 165, 0, 0.5);
}

.summary-item .value.critical {
  color: #ff4444;
  text-shadow: 0 0 8px rgba(255, 68, 68, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chart-header {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .warning-summary {
    flex-direction: column;
    gap: 10px;
  }

  .summary-item {
    width: 100%;
  }

  .summary-item .value {
    font-size: 14px;
  }
}
</style>
